<?php
namespace api\modules\v1\models\redPacket;

use api\modules\v1\models\user\User;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\Status;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;


class RedPacketLog extends \common\models\redPacket\RedPacketLog
{

    /**
     * 领取记录
     * @param int $id
     * @return array
     */
    public function getReceiveList($id = 0) {
        $redis = Yii::$app->redis;
        $user = (new User()) -> checkUser();
        try{

            if (empty($id)) {
                throw new Exception('参数错误');
            }


//            $redPacketInfo = $redis->get(CacheKeys::IM_RED_PACKET.$id);
//            $redPacketInfo = json_decode($redPacketInfo,true);

            $redPacketInfo = RedPacket::getOneInfoById($id,['user_id','money','num','receive_num','name','status','finish_time','create_time']);
            if (!$redPacketInfo) {
                throw new Exception('红包不存在！');
            }



            $userInfo = User::getObjectByWhere(['id' => $redPacketInfo['user_id']],['id','login_name','user_face','nick_name','tx_code','user_code'])->with([
            ])->asArray()->one();

            $resultUser['user_face'] = static::getAvatar($userInfo['user_face']) ?? '';
            $resultUser['user_nick_name'] = $userInfo['nick_name'] ?? '';
            $resultUser['user_tx_code'] = $userInfo['tx_code'] ?? '';
            $resultUser['receive_money'] = 0;

            $where = $andWhere = [];
            $where['red_packet_id'] = $id;
            $where['status'] = Status::RED_PACKET_DONE;

            $list = static::getObjectByAndWhere($where, $andWhere, ['*'], 'id DESC')->with(
//                [
//                'receiveUser' => function ($q) {
//                    $q->select(['id','login_name','user_face','nick_name','tx_code','user_code']);
//                },
//            ]
            )->asArray()->all();

            $result = [];
            $isReceive = false;
            foreach ($list as $v) {

                $result[] = [
                    'id' => (int) $v['id'],
                    'red_packet_id' => (int) $v['red_packet_id'],
                    'red_packet_name' => $v['name'],
                    'num' => $v['num'] ?: '',
                    'money' => $v['money'] ?: '',
                    'type' => $v['type'] ?: '',
                    'status' => $v['status'] ?: '',
                    'is_max' => $v['is_max'] ?: '',
                    'one_money' => $v['receive_money'] ?: '',

                    'tx_code' => $v['receive_user_tx_code'],
//                    'tx_code' => $singleUserInfo['tx_code'],
                    'face' => static::getAvatar($v['receive_user_face']),
                    'nick_name' => $v['receive_user_nick_name'] ?? '',
                    'time' => strtotime($v['finish_time']),
                ];

                if ($v['receive_user_id'] == $user['id']) {
                    $resultUser['receive_money'] = $v['receive_money'];
                    $isReceive = true;
                }
            }

            if ($redPacketInfo['status'] != Status::RED_PACKET_DONE) {
                if (($redPacketInfo['user_id'] != $user['id']) && !$isReceive) {
                    throw new Exception('红包不可查看！');
                }
            }

            $data['user'] = $resultUser;
            $data['list'] = $result;
            $data['red_packet'] = [
                'money' => $redPacketInfo['money'],
                'total_num' => $redPacketInfo['num'],
                'receive_num' => $redPacketInfo['receive_num'],
                'name' => $redPacketInfo['name'],
                'is_done' => $redPacketInfo['status'] == Status::RED_PACKET_DONE,
                'duration_time' => $redPacketInfo['finish_time'] ?
                    Functions::diffDateTime(date("Y-m-d H:i:s",(strtotime($redPacketInfo['create_time']))),date("Y-m-d H:i:s",(strtotime($redPacketInfo['finish_time']))))."被抢光"
                    : '',
            ];


            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 红包记录
     * @return array
     */
    public function getList() {
        $redis = Yii::$app->redis;
        $user = (new User()) -> checkUser();
        try{
            $page = (int) Yii::$app->request->get('page',1);
            $size = (int) Yii::$app->request->get('size',20);
            $type = (string) Yii::$app->request->get('type',0);
            $where = $andWhere = [];
            $where['status'] = Status::RED_PACKET_DONE;
            if ($type == 1) {
                // 收到的
                $where['receive_user_id'] = $user['id'];
            } else {
                // 发出的
                $where['user_id'] = $user['id'];
            }

            $count = static::getCountByAndWhere($where,$andWhere);
            $data = static::setPageinationAPI($page, $size, $count);

            $offset = ($page - 1) * $size;
            $list = static::getObjectByAndWhere($where, $andWhere, ['*'], 'id DESC', $offset, $size)->with(
                [
//                'sendUser' => function ($q) {
//                    $q->select(['id','login_name','user_face','nick_name','tx_code','user_code']);
//
//                },
                ]
            )->asArray()->all();

            $result = [];
            foreach ($list as $v) {
                $singleSendUserInfo = ArrayHelper::getValue($v,'sendUser',[]);
                $result[] = [
                    'id' => (int) $v['id'],
                    'red_packet_id' => (int) $v['red_packet_id'],
                    'red_packet_name' => $v['name'],
                    'money' => $v['money'] ?: '',
                    'one_money' => $v['receive_money'] ?: '',

//                    'tx_code' => $singleSendUserInfo['tx_code'],
//                    'face' => static::getAvatar($singleSendUserInfo['user_face']),
//                    'nick_name' => $singleSendUserInfo['nick_name'] ?? '',
                    'time' => strtotime($v['finish_time']),
                ];
            }


            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

}
